from django_redis import get_redis_connection
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer


class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        # Add custom claims
        token['avatar'] = user.avatar.url if user.avatar else ""
        token['nickname'] = user.nickname
        token['money'] = float(user.money)
        token['credit'] = user.credit

        # 返回购物车的商品数量
        redis = get_redis_connection("cart")
        cart_total = redis.hlen(f"cart_{user.id}")
        token['cart_total'] = cart_total

        return token
